package com.ldc.framework.fragment

import android.os.Bundle
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.listener.OnRowListener2
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.MessageUts
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMFragment
import com.ldc.framework.adapter.ArticleAdapter
import com.ldc.framework.databinding.FrameworkFragmentQABinding
import com.ldc.framework.model.ArticleModel
import com.ldc.framework.viewmodel.FrameworkViewModelBase
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener


class QAFragment : VBMFragment<FrameworkFragmentQABinding, FrameworkViewModelBase>() {
    private var currPage: Int = 0
    private var articleAdapter: ArticleAdapter? = null


    override fun processMessage(msg: Message): Boolean {
        when (msg.what) {
            REFRESH_CODE -> {
                topArticleList()
            }
        }
        return super.processMessage(msg)
    }

    companion object {
        private const val REFRESH_CODE = 0x1010
        private const val ARG_USER_ID: String = "ARG_USER_ID"
        fun newInstance(userId: String = ""): QAFragment = QAFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_USER_ID, userId)
            }
        }
    }

    override fun main() {
        initAdapter()
        viewBind?.statusView?.let {
            it.showLoadView()
            it.addRetryClickListener(object : OnRowListener<Int> {
                override fun onRow(v: View, data: Int) {
                    it.showLoadView("正在重试，请稍等")
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }
            })
        }
        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FrameworkFragmentQABinding = FrameworkFragmentQABinding.inflate(inflater, container, false)

    override fun createViewModel(): FrameworkViewModelBase =
        ViewModelUtils.create(this, FrameworkViewModelBase::class.java)

    private fun initAdapter() {
        articleAdapter = ArticleAdapter().also { adapter ->
            adapter.addCollectRowListener(object : OnRowListener2<ArticleModel, Int> {
                override fun onRow(v: View, data: ArticleModel, data2: Int) {
                    if (data.collect) {
                        // 取消收藏
                        viewModel?.uncollectOriginId("${data.id}")
                            ?.observe(this@QAFragment) {
                                if (ApiUtils.isSuccess(it)) {
                                    adapter.changeDataItem(data2)
                                }
                            }
                    } else {
                        // 收藏
                        viewModel?.collect("${data.id}")?.observe(this@QAFragment) {
                            if (ApiUtils.isSuccess(it)) {
                                adapter.changeDataItem(data2)
                            }
                        }
                    }
                }
            })
            adapter.addOnRowListener(object : OnRowListener<ArticleModel> {
                override fun onRow(v: View, data: ArticleModel) {
                    // 点击事件
                    ARouter.getInstance().build(RouteConf.WebViewRoute.startEnter)
                        .withString(AppConf.ARG_TITLE, data.title)
                        .withString(AppConf.ARG_URL, data.link)
                        .navigation()
                }
            })
        }
        viewBind?.rfRv?.let {
            it.refreshView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                override fun onRefresh(refreshLayout: RefreshLayout) {
                    currPage = 0
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }

                override fun onLoadMore(refreshLayout: RefreshLayout) {
                    currPage += 1
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }
            })
            it.rv.recyclerview.let { rv ->
                rv.adapter = articleAdapter
                rv.layoutManager =
                    LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
                rv.setHasFixedSize(true)
            }
        }
    }

    // 获取首页文章
    private fun topArticleList() {
        viewModel?.wenDa(currPage)?.observe(this) { data ->
            viewBind?.statusView?.showContentView()
            viewBind?.rfRv?.refreshView?.let { rv ->
                if (rv.state.isOpening) {
                    rv.finishRefresh()
                    rv.finishLoadMore()
                }
                rv.setNoMoreData(currPage == data.data?.pageCount)
            }
            if (ApiUtils.isSuccess(data)) {
                articleAdapter?.let { adapter ->
                    if (0 == currPage) {
                        adapter.newData(data.data?.datas)
                    } else {
                        adapter.addNewData(data.data?.datas)
                    }
                }
            } else {
                viewBind?.statusView?.showErrorView(data.errorMsg)
            }
        }
    }

}